package com.xt.purchasingsystem.aspect;

import com.xt.purchasingsystem.annotation.PurchaseClearCache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * redis清空缓存切面类
 * @author: 老姚
 * Date:  2020/5/24 11:42
 */
@Component
@Aspect
public class PurchaseClearCacheAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;
   @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Before("@annotation(com.xt.purchasingsystem.annotation.PurchaseClearCache)")
    public void before(JoinPoint joinPoint) {
        //异步把数据从redis中删除
        CompletableFuture.runAsync(() -> {
            // 获取连接点签名
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            // 获取连接点的GmallCache注解信息
            PurchaseClearCache purchaseClearCache = method.getAnnotation(PurchaseClearCache.class);
            String[] prefixs = purchaseClearCache.prefix();
            for (String prefix : prefixs) {
                Set<String> keys = redisTemplate.keys(prefix + "*");
                redisTemplate.delete(keys);
            }
       }, threadPoolExecutor);



    }

}
